package com.twu.biblioteca.view.consoleUI;

import com.twu.biblioteca.model.Book;
import com.twu.biblioteca.model.Movie;
import com.twu.biblioteca.model.menu.Command;
import com.twu.biblioteca.model.menu.Menu;
import com.twu.biblioteca.view.UI;
import com.twu.biblioteca.view.consoleUI.viewActions.*;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;

public class ConsoleUI extends UI {


    private final Scanner input;
    private final PrintStream output;
    private final Menu menu;


    public ConsoleUI(Menu menu, InputStream input, PrintStream output) {
        this.menu = menu;
        this.input = new Scanner(input);
        this.output = output;
        createViewActions();
    }

    @Override
    public void showOptions() {
        for (Command command : menu.getValidCommands())
            output.println(command.getKey() + ": " + command.getText());
    }

    @Override
    public void welcome() {
        output.println("Welcome to Biblioteca!");
    }

    @Override
    public Command getCommand() {
        if (input.hasNextLine()) {
            String line = input.nextLine();
            for (Command command : menu.getValidCommands()) {
                if (command.getKey().equalsIgnoreCase(line))
                    return command;
            }
            output.println("Select a valid option!");
        }
        return null;
    }

    @Override
    public String[] getQuestionAnswers(Command command) {
        if (command.getQuestions() != null) {
            String[] params = new String[command.getQuestions().length];
            for (int i = 0; i < params.length; i++) {
                output.println(command.getQuestions()[i]);
                params[i] = input.nextLine();
            }
            return params;
        }
        return null;
    }

    public PrintStream getOutput() {
        return output;
    }

    private void createViewActions() {
        this.getViewActions().put(Command.VIEW_DETAILS, new ViewDetailsViewAction(output, menu));
        this.getViewActions().put(Command.LOGIN, new LoginViewAction(this));
        this.getViewActions().put(Command.QUIT, new QuitViewAction(output));
        this.getViewActions().put(Command.LIST_BOOK, new ListViewAction(output, menu, Book.class));
        this.getViewActions().put(Command.CHECKOUT_BOOK, new CheckoutViewAction(output, Book.class));
        this.getViewActions().put(Command.RETURN_BOOK, new ReturnViewAction(output, Book.class));

        this.getViewActions().put(Command.LIST_MOVIE, new ListViewAction(output, menu, Movie.class));
        this.getViewActions().put(Command.CHECKOUT_MOVIE, new CheckoutViewAction(output, Movie.class));
        this.getViewActions().put(Command.RETURN_MOVIE, new ReturnViewAction(output, Movie.class));

    }
}
